"""
    数据库操作封装类
"""
# 定义数据库工具类
import pymysql

class DBUtil:
    conn = None
    # 创建连接
    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            # 连接数据库
            cls.conn = pymysql.connect(host="localhost", port=3306, user="root", password="1234", database="sky_take_out",
                                   charset="utf8")
        return cls.conn

    # 关闭连接
    @classmethod
    def __close_conn(cls):
        # 判断conn是否为空，不为空则需要关闭
        if cls.conn is not None:
            cls.conn.close()
            # 置空
            cls.conn = None

    # 查询一条语句
    @classmethod
    def select_one(self,sql):
        cursor = None
        result = None
        try:
            # 创建连接
            self.conn = self.__get_conn()
            # 获取游标
            cursor = self.conn.cursor()
            # 执行查询一条的语句
            cursor.execute(sql)
            # 查询一条语句
            result = cursor.fetchone()
        except Exception as e:
            print("查询一条语句时出现异常"+str(e))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            self.__close_conn()
            return result

    # 增删改操作
    @classmethod
    def uid_db(cls,sql):
        cursor = None
        result = None
        try:
            # 创建连接
            cls.conn = cls.__get_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 提交事务
            cls.conn.commit()
        except Exception as e:
            print("执行sql语句时出现异常" + str(e))
            # 回滚操作
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_conn()





